<?php

namespace app\api\service;

use app\common\model\tang\Config;
use app\common\model\tang\Cost;
use app\common\model\tang\Invoice;
use app\common\model\tang\InvoiceLog;

class GPService
{
    protected static $appId = "";
//    protected static $appId = "3a8d210a4bdc9eb015245657afb9aea4b9a83ff482b6c9defe1a32db4ad59a29";
    protected static $contentPassword = '';
//    protected static $contentPassword = '3516AD05A4418F00';
    protected static $CodeUrl = '';
//    protected static $CodeUrl = 'https://dev.fapiao.com:18944/fpt-dsqz/services/DZFPJsonService?wsdl';
    protected static $interfaceCode = 'DFXJ1001';//开票code
    protected static $blush = 'DFXJ1008';//冲红
    public function getConfig(){
        $config = (new Config())->find(1);
        static::$appId= trim($config['invoice_account']);
        static::$contentPassword = trim($config['invoice_password']);
        static::$CodeUrl = trim($config['invoice_url']);
    }
    /**
     * 冲红
     */
    public function blush($contentData){
        $this->getConfig();
        $reqXML = $this->getSendToTaxXML(static::$appId, static::$contentPassword, static::$blush, $contentData);
        $cerarr = array(
            'local_cert' => app()->getRootPath() . "public/cret/testISSUE.pem",
            'passphrase' => '123456'
        );
        $client = new \SoapClient(static::$CodeUrl, $cerarr);
        $result = $client->doJsonService([
            'in0' => $reqXML
        ]);

        $str = $this->object_array($result, true);
        $fa_info = $str['out'];
        $result = json_decode($fa_info, true);
        if ($result['interface']['returnStateInfo']['returnCode'] == '0000') {
            $fapiao_info = json_decode(base64_decode($result['interface']['Data']['content']), true);
            $invoiceModel = (new Invoice());
            $invoiceModel->update([
                'BlushCode' => $fapiao_info['FP_DM'],
                'BlushNo' => $fapiao_info['FP_HM'],
                'Blush_SP_URL' => $fapiao_info['SP_URL'],
                'BlushpdfUrl' => $fapiao_info['PDF_URL'],
                'status' => 3,
            ], ['invoiceBlush' => $fapiao_info['FPQQLSH']]);
        }
        return $result['interface']['returnStateInfo'];
    }
    /**
     *开票接口
     */
    public function doJsonService($contentData)
    {
        $this->getConfig();
        $log = (new InvoiceLog());
//            软证书配置变量，此处软证书配置可以不填写
        try {
            $reqXML = $this->getSendToTaxXML(static::$appId, static::$contentPassword, static::$interfaceCode, $contentData);
            $cerarr = array(
                'local_cert' => app()->getRootPath() . "public/cret/testISSUE.pem",
                'passphrase' => '123456'
            );
            $client = new \SoapClient(static::$CodeUrl, $cerarr);
            //调用doService方法, doJsonService
            $result = $client->doJsonService([
                'in0' => $reqXML
            ]);
            //将stdClass Object转换成array格式
            $str = $this->object_array($result, true);
            $fa_info = $str['out'];
            $result = json_decode($fa_info, true);
            if ($result['interface']['returnStateInfo']['returnCode'] == '0000') {
                $fapiao_info = json_decode(base64_decode($result['interface']['Data']['content']), true);
                $invoiceModel = (new Invoice());
                $invoiceModel->update([
                    'invoiceCode' => $fapiao_info['FP_DM'],
                    'invoiceNo' => $fapiao_info['FP_HM'],
                    'SP_URL' => $fapiao_info['SP_URL'],
                    'pdfUrl' => $fapiao_info['PDF_URL'],
                    'invoiceTime' => $fapiao_info['KPRQ'],
                    'JYM' => $fapiao_info['JYM'],
                    'status' => 1,
                ], ['invoiceSerialNum' => $fapiao_info['FPQQLSH']]);
                $costModel = new Cost();
                $costId = $invoiceModel->where('invoiceSerialNum',$fapiao_info['FPQQLSH'])->value('costId');
                if(!empty($costId)){
                    $costModel->whereIn('id',explode(',',$costId))->update(['invoice'=>1]);
                }
                $log->send_info = json_encode($contentData);
                $log->return_info = json_encode($result);
                $log->save();
                (new Config())->where('id',1)->dec('invoicesum', 1)->update();
                (new Config())->where('id',1)->inc('wuye', 1)->update();
            } else {
                $log = (new InvoiceLog());
                $log->send_info = json_encode($contentData);
                $log->return_info = json_encode($result['interface']['returnStateInfo']);
                $log->save();
            }
            return $result['interface']['returnStateInfo'];
        } catch (\Exception $exception) {
//            throw new \Exception('开票异常');
            throw new \Exception($exception->getMessage());
        }
    }
    /**
     * 新cremb开票接口
     */
    public function doJsonServiceNew($contentData){
        $this->getConfig();
//        $appId = '3a8d210a4bdc9eb015245657afb9aea4b9a83ff482b6c9defe1a32db4ad59a29';
//        $contentPassword = '3516AD05A4418F00';
//        $CodeUrl = 'https://dev.fapiao.com:18944/fpt-dsqz/services/DZFPJsonService?wsdl';
//            软证书配置变量，此处软证书配置可以不填写
        try {
            $reqXML = $this->getSendToTaxXML(static::$appId, static::$contentPassword, static::$interfaceCode, $contentData);
//            $reqXML = $this->getSendToTaxXML($appId,$contentPassword, static::$interfaceCode, $contentData);
            $cerarr = array(
                'local_cert' => app()->getRootPath() . "public/cret/testISSUE.pem",
                'passphrase' => '123456'
            );
            $client = new \SoapClient(static::$CodeUrl, $cerarr);
//            $client = new \SoapClient($CodeUrl, $cerarr);
            //调用doService方法, doJsonService
            $result = $client->doJsonService([
                'in0' => $reqXML
            ]);
            //将stdClass Object转换成array格式
            $str = $this->object_array($result, true);
            $fa_info = $str['out'];
            $result = json_decode($fa_info, true);
            if ($result['interface']['returnStateInfo']['returnCode'] == '0000') {
                (new Config())->where('id',1)->inc('tingche', 1)->update();
                (new Config())->where('id',1)->dec('invoicesum', 1)->update();
            }
            return $result;
        } catch (\Exception $exception) {
//            throw new \Exception('开票异常');
            throw new \Exception($exception->getMessage());
        }
    }
    /**
     *组装数据
     */
    public function getSendToTaxXML($appId, $contentPassword, $interfaceCode, $contentData)
    {
        $contentData = base64_encode(json_encode($contentData));
        $contentKey = base64_encode(openssl_encrypt(md5($contentData), 'aes-128-ecb', $contentPassword, OPENSSL_RAW_DATA));
        $str = [
            'interface' => [
                'globalInfo' => [
                    'interfaceCode' => $interfaceCode,
                    'responseCode' => 'DZFPQZ',
                    'appId' => $appId,
                    'requestTime' => date('Y-m-d H:i:s', time()),
                    'requestCode' => 'DS',
                    'interfaceId' => '',
                    'dataExchangeId' => 'DZFPQZ'.$interfaceCode . date('Y-m-d') . rand(111111111, 999999999),
                ],
                'returnStateInfo' => [
                    'returnCode' => '',
                    'returnMessage' => ''
                ],
                'Data' => [
                    'dataDescription' => [
                        'zipCode' => "0"
                    ],
                    'content' => $contentData,
                    'contentKey' => $contentKey
                ]
            ]
        ];
        return json_encode($str);
    }

    public function object_array($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }
}